package edu.nazarevych.portal.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.map.LinkedMap;
import org.hibernate.classic.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.nazarevych.portal.dao.HibernateSessionFactory;
import edu.nazarevych.portal.dao.RolesDao;
import edu.nazarevych.portal.entities.Roles;
import edu.nazarevych.portal.entities.User;

@Controller
@RequestMapping("users/add")
public class UserFormController {
	
	private static final Logger logger = LoggerFactory
			.getLogger(UserFormController.class);
	
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map model) {
		RolesDao dao = new RolesDao();
		List<Roles> rolesList = dao.findAll();
//		Map<Roles, String> rolesList = new LinkedMap();
//		for (Roles role : list) {
//			rolesList.put(role, role.getRoleName());
//		}
		User user = new User();
		model.put("user", user);
		model.put("rolesList", rolesList);
		return "userForm";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(@Valid User user, BindingResult result,
			Map model) {
		if (result.hasErrors()) {
			return "userForm";
		}
		user = (User) model.get("user");
		model.put("user", user);
		saveUser(user);
		return "userFormResult";
	}
	
	private void saveUser (User user){
		Session session = HibernateSessionFactory.sessionFactory.openSession();
		session.saveOrUpdate(user);
		logger.info("saved user" + user.toString());
		session.close();
	}

}